package com.wttm.client;

import com.google.gwt.core.client.EntryPoint;
import com.google.gwt.core.client.GWT;
import com.google.gwt.user.client.Window;
import com.google.gwt.user.client.rpc.AsyncCallback;
import com.google.gwt.user.client.ui.Anchor;
import com.google.gwt.user.client.ui.Label;
import com.google.gwt.user.client.ui.RootPanel;
import com.google.gwt.user.client.ui.VerticalPanel;
import com.wttm.shared.LoginInfo;
import com.wttm.shared.NotLoggedInException;

/**
 * Entry point classes define <code>onModuleLoad()</code>.
 */
public class WalkToTheMoon implements EntryPoint {
	
	private LoginInfo loginInfo = null;
	private final LoginServiceAsync loginService = GWT.create(LoginService.class);

	/**
	 * This is the entry point method.
	 */
	public void onModuleLoad() {
		loginService.login(GWT.getHostPageBaseURL(), new AsyncCallback<LoginInfo>() {
			public void onFailure(Throwable error) {
				handleError(error);
			}

			public void onSuccess(LoginInfo result) {
				loginInfo = result;
				if (loginInfo.isLoggedIn()) {
					loadWelcomePage();
				} else {
					loadLogin();
				}
			}
		});
	}
	
	private void loadLogin() {
		// Assemble login panel.
		VerticalPanel loginPanel = new VerticalPanel();
		Label loginLabel = new Label("Please sign in to your Google Account to access the StockWatcher application.");
		Anchor signInLink = new Anchor("Sign In");
		signInLink.setHref(loginInfo.getLoginUrl());
		
		loginPanel.add(loginLabel);
		loginPanel.add(signInLink);
		
		RootPanel.get("content").add(loginPanel);
	}
	
	private void loadWelcomePage() {
		new WelcomePage(loginInfo);
	}
	
	
	private void handleError(Throwable error) {
		Window.alert(error.getMessage());
		if(error instanceof NotLoggedInException) {
			Window.Location.replace(loginInfo.getLogoutUrl());
		}
	}
	
}
